package com.tjcm.tjcminspectmanager;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPOutputStream;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import cn.emagsoftware.ui.adapterview.DataHolder;
import cn.emagsoftware.ui.adapterview.GenericAdapter;
import cn.emagsoftware.ui.adapterview.ViewHolder;
import cn.emagsoftware.ui.dialog.DialogManager;
import cn.emagsoftware.ui.staticmanager.StaticManager;
import cn.emagsoftware.util.FileUtilities;
import cn.emagsoftware.util.LogManager;
import cn.emagsoftware.util.StringUtilities;

import com.tjcm.tjcminspectmanager.manager.GPSManager;
import com.tjcm.tjcminspectmanager.manager.NetManager;
import com.tjcm.tjcminspectmanager.manager.SPManager;
import com.tjcm.tjcminspectmanager.model.User;

public class MainActivity extends BaseActivity
{

    static BackgroundTask backgroundTask = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (!LoginActivity.IS_APP_RUNNING)
        {
            StaticManager.restartAppWhenDalvikRecycled(this, LoginActivity.class);
            return;
        }
        final User user = (User) getIntent().getSerializableExtra("USER");
        setContentView(R.layout.main);
        GridView grid = (GridView) findViewById(R.id.grid);
        List<DataHolder> holders = new ArrayList<DataHolder>();
        for (int i = 0; i < 7; i++)
        {
            int iconId = -1;
            int descId = -1;
            if (i == 0)
            {
                iconId = R.drawable.main_item_xjdcj;
                descId = R.string.main_item_xjdcj;
            } else if (i == 1)
            {
                iconId = R.drawable.main_item_rwcl;
                descId = R.string.main_item_rwcl;
            } else if (i == 2)
            {
                iconId = R.drawable.main_item_jhcl;
                descId = R.string.main_item_jhcl;
            } else if (i == 3)
            {
                iconId = R.drawable.main_item_yhsb;
                descId = R.string.main_item_yhsb;
            } else if (i == 4)
            {
                iconId = R.drawable.main_item_yhcx;
                descId = R.string.main_item_yhcx;
            } else if (i == 5)
            {
                iconId = R.drawable.main_item_gpscx;
                descId = R.string.main_item_gpscx;
            } else if (i == 6)
            {
                iconId = R.drawable.main_item_gyxt;
                descId = R.string.main_item_gyxt;
            }
            holders.add(new DataHolder(new int[] { iconId, descId }, 0)
            {
                @Override
                public View onCreateView(Context arg0, int arg1, Object arg2)
                {
                    // TODO Auto-generated method stub
                    View item = LayoutInflater.from(arg0).inflate(R.layout.main_item, null);
                    item.setTag(new ViewHolder(item.findViewById(R.id.icon), item.findViewById(R.id.desc)));
                    onUpdateView(arg0, arg1, item, arg2);
                    return item;
                }

                @Override
                public void onUpdateView(Context arg0, int arg1, View arg2, Object arg3)
                {
                    // TODO Auto-generated method stub
                    View[] views = ((ViewHolder) arg2.getTag()).getParams();
                    int[] resIds = (int[]) arg3;
                    ((ImageView) views[0]).setImageResource(resIds[0]);
                    ((TextView) views[1]).setText(resIds[1]);
                }

                @Override
                public void onAsyncDataExecuted(Context arg0, int arg1, View arg2, Object arg3, int arg4)
                {
                    // TODO Auto-generated method stub
                }
            });
        }
        GenericAdapter gridAdapter = new GenericAdapter(this, holders);
        grid.setAdapter(gridAdapter);
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
            {
                // TODO Auto-generated method stub
                if (arg2 == 0)
                {
                    Intent intent = new Intent(MainActivity.this, PointCollectActivity.class);
                    intent.putExtra("USER", user);
                    startActivity(intent);
                } else if (arg2 == 1)
                {
                    Intent intent = new Intent(MainActivity.this, TaskSelectActivity.class);
                    intent.putExtra("USER", user);
                    startActivity(intent);
                } else if (arg2 == 2)
                {
                    Intent intent = new Intent(MainActivity.this, PlanListActivity.class);
                    intent.putExtra("USER", user);
                    startActivity(intent);
                } else if (arg2 == 3)
                {
                    Intent intent = new Intent(MainActivity.this, TroubleReportActivity.class);
                    intent.putExtra("USER", user);
                    startActivity(intent);
                } else if (arg2 == 4)
                {
                    Intent intent = new Intent(MainActivity.this, TroubleQueryActivity.class);
                    intent.putExtra("USER", user);
                    startActivity(intent);
                } else if (arg2 == 5)
                {
                    Intent intent = new Intent(MainActivity.this, GPSQueryActivity.class);
                    startActivity(intent);
                } else if (arg2 == 6)
                {
                    PackageInfo pi = null;
                    try
                    {
                        pi = getPackageManager().getPackageInfo(getPackageName(), 0);
                    } catch (NameNotFoundException e)
                    {
                        throw new RuntimeException(e);
                    }
                    DialogManager.showAlertDialog(MainActivity.this, getString(R.string.main_item_gyxt_title), StringUtilities.replaceWordsAll(getString(R.string.main_item_gyxt_msg), "{0}",
                            pi.versionName), new String[] { getString(R.string.generic_dialog_btn_ok) }, null, true, false);
                }
            }
        });
        if (backgroundTask == null)
        {
            backgroundTask = new BackgroundTask();
            backgroundTask.execute(getApplicationContext());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // TODO Auto-generated method stub
        if (item.getItemId() == R.id.quit)
        {
            finish();
            return true;
        } else if (item.getItemId() == R.id.background)
        {
            Intent intent = new Intent(this, UploadListActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public static class BackgroundTask extends AsyncTask<Context, Object, Object>
    {
        private boolean isRunning = true;

        @Override
        protected Object doInBackground(Context... params)
        {
            // TODO Auto-generated method stub
            while (true)
            {
                if (!isRunning)
                {
                    try
                    {
                        Thread.sleep(5000);
                    } catch (InterruptedException e)
                    {
                    }
                    continue;
                }
                String fileName = SPManager.peekUploadTaskQueue(params[0]);
                if (fileName == null)
                {
                    try
                    {
                        Thread.sleep(5000);
                    } catch (InterruptedException e)
                    {
                    }
                    continue;
                }
                File file = new File(GPSManager.GPS_PATH, fileName);
                if (!file.isFile())
                {
                    LogManager.logE(BackgroundTask.class, "file(" + fileName + ") not found,would pass it.");
                    SPManager.pollUploadTaskQueue(params[0]);
                    continue;
                }
                try
                {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    GZIPOutputStream outputPack = new GZIPOutputStream(output);
                    FileUtilities.readFromFile(file, outputPack, 1024 * 2);
                    outputPack.close();
                    NetManager.sendGPSData(output.toByteArray(), (byte) 28, fileName);
                    SPManager.pollUploadTaskQueue(params[0]);
                    file.delete();
                } catch (Exception e)
                {
                    LogManager.logE(BackgroundTask.class, "upload file(" + fileName + ") failed,would try again later.", e);
                    try
                    {
                        Thread.sleep(5000);
                    } catch (InterruptedException e1)
                    {
                    }
                }
            }
        }

        public void start()
        {
            isRunning = true;
        }

        public void stop()
        {
            isRunning = false;
        }

        public boolean isRunning()
        {
            return isRunning;
        }
    }

}